/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.opgea.crm.web.controller;

import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.opgea.crm.common.constant.ApplicationConstant;
import com.opgea.crm.domain.entities.security.CrmUser;
import com.opgea.crm.domain.modal.JsonModelMap;
import com.opgea.crm.domain.modal.UserSessionData;
import com.opgea.crm.services.security.CrmUserServiceImpl;
import com.opgea.crm.services.security.ResourceDetailsService;

/**
 *
 * @author User1
 */
@Controller
@RequestMapping(value="home")
public class HomeController  {


	@Autowired
	CrmUserServiceImpl userService;
	
	@Autowired
	ResourceDetailsService resourceDetailsService; 
	
    @RequestMapping(method=RequestMethod.GET )
    public ModelAndView show(HttpServletRequest request){
    	return new ModelAndView("header");
    }
    
    @RequestMapping(method=RequestMethod.GET, value="loginDetails")
    public @ResponseBody 
    Map<String, Object> loginDetails(HttpServletRequest request)throws IOException{
    	
    	UserSessionData userSessionData = null;
    	if(resourceDetailsService.getAuthoritiesDetails() != null){
    		userSessionData = resourceDetailsService.getAuthoritiesDetails();
    		CrmUser user = userService.getCrmUser(userSessionData.getUserName());
    		
    		HttpSession session = request.getSession();
        	session.setAttribute(ApplicationConstant.SESSION_USER_DETAILS, userSessionData);
        	session.setAttribute(ApplicationConstant.SESSION_USER, user);
        	String roleName = "";
        	if(userSessionData.getRoleName() != null){
        		roleName = userSessionData.getRoleName();
        	}
        	return JsonModelMap.success().data(userSessionData.getEmailId()+", "+roleName);
    	}else{
    		return JsonModelMap.success().data("User Details Not Found.");
    	}
    }
    
	@RequestMapping(method = RequestMethod.GET, value="getLoginDetails")
	public @ResponseBody
	Map<String, Object> getLoginDetails(HttpServletRequest request){
		HttpSession session = request.getSession(true);
		UserSessionData userDetails = (UserSessionData)session.getAttribute(ApplicationConstant.SESSION_USER_DETAILS);
		return JsonModelMap.success().data(userDetails);
	}

}
